<template>
  <div class="wendouDiv flex-row-start-center">
    <!-- 操作记录 -->
    <div class="operateRecord">
      <div class="operateRecord_title">操作记录</div>
      <div class="operateRecord_Main">
        <span v-for="item in operateRecordList">
          {{item.text}}
        </span>
      </div>
    </div>
    <div class="wendouMain">

      <!-- 高拍仪canvas -->
      <div id="Div1">
        <div id="CameraCtl" />
      </div>

      <!-- <div style="border: 1px dashed #000">
        <input id="Checkbox3" type="checkbox" /> 添加水印 水印内容<input
          id="Text1"
          type="text"
          value="水印测试"
        />
        透明度<input id="Text2" type="text" value="127" style="width: 40px" />
        大小<input id="Text3" type="text" value="80" style="width: 40px" />
        <br />
        位置
        <select id="Select1">
          <option value="0">左上</option>
          <option value="1">右上</option>
          <option value="2">左下</option>
          <option value="3">右下</option>
          <option value="4">中间</option>
        </select>
        颜色
        <select id="Select2">
          <option value="0">红色</option>
          <option value="1">绿色</option>
          <option value="2">蓝色</option>
          <option value="3">青色</option>
          <option value="4">黄色</option>
          <option value="5">白色</option>
          <option value="6">黑色</option>
        </select>
        <input id="Checkbox4" type="checkbox" /> 添加时间水印
        <input
          type="button"
          value="生效水印参数设置"
          onclick="toSetWaterMarkParams()"
        />
      </div> -->


      <div class="wendou_operateList">
        <div class="operateList_title">
          操作列表
        </div>
        <el-button type="primary" @click="GetDrives">获取盘符</el-button>
        <!-- <input type="button" value="放大" onclick="Cam_ZoomIn();" /> -->
        <!-- <input type="button" value="缩小" onclick="Cam_ZoomOut();" /> -->
        <!-- <input type="button" value="适屏" onclick="Cam_BestSize();" /> -->
        <!-- <input type="button" value="1:1" onclick="Cam_TrueSize();" /> -->
        <el-button type="primary" @click="Cam_RotateLeft">左旋</el-button>
        <el-button type="primary" @click="Cam_RotateRight">右旋</el-button>
        <el-button type="primary" @click="TakePhoto">拍照</el-button>
        <!-- <input type="button" value="对焦" onclick="Cam_Focus();" /> -->
        <el-button type="primary" @click="Cam_ShowVideoProp">设置</el-button>
        <!-- <input type="button" value="读身份证" @click="GetIdCardInfo" /> -->
        <el-button type="primary" @click="GetIdCardInfo">读身份证</el-button>

        <!-- <input
          type="button"
          value="从摄像头中识别二维码"
          onclick="RecogQrCodeFromCamera(1);"
        /> -->
        <!-- <input
          type="button"
          value="从图片中识别二维码"
          onclick="RecogBarCodeFromFile(1);"
        /> -->
        <el-button type="primary" @click="ToAddPDFFile">添加合并PDF文件</el-button>
        <el-button type="primary" @click="ToCombinePDF">合并PDF</el-button>
        <el-button type="primary" @click="ToAddMergeImageFile">添加合并图像文件</el-button>
        <el-button type="primary" @click="ToMergeImages">合并图像</el-button>
        <el-button type="primary" @click="ToDeleteFile">删除文件</el-button>

        <!-- <input type="button" value="上传" onclick="HttpUploadFile();" /> -->
        <!-- <input type="button" value="上传2" onclick="HttpUploadFile2();" /> -->
      </div>
    </div>


      <!-- <div class="">
        设备
        <select
          style="width: 140px"
          id="DevName"
          @change="SelectDevice()"
          v-model="deviceOption"
        >
          <option
            v-for="(item, index) in deviceOptions"
            :value="item.value"
            :key="index"
          >
            {{ item.value == 0 ? "主摄像头" : "负设想头" }}
          </option>
        </select>
        分辨率
        <select
          style="width: 140px"
          id="DevResolution"
          @change="SelectResolution()"
          v-model="deviceResolution"
        >
          <option
            v-for="(item, index) in deviceResolutions"
            :value="item.value"
            :key="index"
          >
            {{ item.text }}
          </option>
        </select>
        <input type="button" value=" 打开设备 " @click="toOpenCamera()" />
        <input type="button" value=" 关闭设备 " @click="toCloseCamera()" />

        裁切模式:
        <el-radio-group @change="SetCameraCutMode" v-model="clippingMode">
          <el-radio :label="0" :value="0">不裁剪</el-radio>
          <el-radio :label="2" :value="2">手动裁剪</el-radio>
          <el-radio :label="1" :value="1">自动裁剪</el-radio>
        </el-radio-group>

        文件格式:
        <el-select
          v-model="filetype"
          @change="toSetFileType()"
          placeholder="请选择"
        >
          <el-option
            v-for="item in fileTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>

        色彩模式:
        <select v-model="colorModeId" @change="toSetColorModel()">
          <option :value="0">彩色</option>
          <option :value="1">灰度</option>
          <option :value="2">黑白</option>
        </select>

        图像质量:
        <select v-model="jpgQualityId" @change="toSetJpgQuality()">
          <option :value="10">10</option>
          <option :value="20">20</option>
          <option :value="30">30</option>
          <option :value="40">40</option>
          <option :value="50">50</option>
          <option :value="60" selected="true">60</option>
          <option :value="70">70</option>
          <option :value="70">80</option>
          <option :value="80">90</option>
          <option :value="100">100</option>
        </select>

        <input
          id="Checkbox1"
          type="checkbox"
          onclick="toSetDeleteBlackEdge()"
        />
        去黑边
        <input id="Checkbox2" type="checkbox" onclick="toSetDeleteBgColor()" />
        去底色 
      </div>-->

    <div
      style="
        width: 202px;
        height: 702px;
        border: 1px solid white;
        background: #dedebe;
        font-size: 14px;
        float: left;
      "
    >
      拍照图片
      <br />
      <img id="CameraPhoto" src="" style="width: 200px; height: 150px" />
      <br /><br /><br />
      身份证信息
      <br />
      <img id="IdCardPhoto" src="" style="width: 80px; height: 100px" />
      <br />
      姓名
      <input
        id="CardName"
        v-model="IDCardObject.name"
        type="text"
        style="width: 100px"
      />
      <br />
      性别
      <input
        id="CardSex"
        v-model="IDCardObject.sex"
        type="text"
        style="width: 100px"
      />
      <br />
      民族
      <input
        id="CardNation"
        v-model="IDCardObject.nation"
        type="text"
        style="width: 100px"
      />
      <br />
      出生
      <input
        id="CardBorn"
        v-model="IDCardObject.birth"
        type="text"
        style="width: 100px"
      />
      <br />
      住址
      <br />
      <textarea
        id="CardAddress"
        cols="20"
        rows="3"
        style="width: 192px"
        v-model="IDCardObject.register"
      ></textarea>
      身份证号码
      <br />
      <input
        id="CardNum"
        v-model="IDCardObject.idCard"
        type="text"
        style="width: 192px"
      />
      <br />
      签发机关
      <input id="CardIssuedAt" type="text" style="width: 135px" /> <br />
      有效期限
      <input id="CardEffectDate" type="text" style="width: 135px" /> <br />
    </div>
  </div>
</template>

<script>
// import wsConnection from "@/unit/webSocket.ts";

export default {
  data() {
    return {
      MainCanvas: null, // 画布
      MainContext: null,
      MainCamCutMode: 0,
      // websocket
      url: "ws://127.0.0.1:22225",
      ws: null,
      connected: false,
      isSocketConnect: false,
      heartTimerId: -1,
      intervalId: -1, // 掉线重连
      // 文件路劲
      path: null,
      // 图片路径
      imgPath: "",
      // 设备列表及默认选择
      deviceOptions: [],
      deviceOption: 0,
      // 设备分辨率列表及默认选择
      deviceResolutions: [],
      deviceResolution: 0,
      // 裁剪模式
      clippingMode: 0,
      // 文件类型列表及默认选项
      fileTypes: [
        { value: 0, label: "jpg" },
        { value: 1, label: "png" },
        { value: 2, label: "tif" },
        { value: 3, label: "pdf" },
      ],
      filetype: 0,
      // 色彩模式
      colorModeId: 0,
      // 图片质量
      jpgQualityId: 60,
      // 身份证信息
      IDCardObject: {
        name: "", // 姓名
        sex: "", // 性别
        nation: "", // 名族
        birth: "", // 出生日期
        register: "", // 户籍地址
        idCard: "", // 身份证
      },
      // 合并图片的张数限制
      MergeCount: 0,
      // 是否点击了鼠标
      isMouseDown: false,
      // 鼠标位置
      pALastX: 0,
      pALastY: 0,
      pACurrentX: 0,
      pACurrentY: 0,
      operateRecordList:[]
    };
  },
  created() {
    /* 昵称： bfhm
       密码： 123456
 */
    // this.LoadCameraDocument();
    // const url = 'ws://127.0.0.1:22225'
  },

  mounted() {
    // this.LoadCameraDocument();
  },

  methods: {
    /***********************************************操作******************************************************************/
    // 设置
    Cam_ShowVideoProp(){
      const data = JSON.stringify({ 'function': 'Cam_ShowVideoProp' });
      this.sendMessage(data)
    },
    // 切换摄像头
    SelectDevice() {
      this.Cam_GetDevResolution(this.deviceOption);
    },
    // 切换分辨率
    SelectResolution() {
      let restr = this.deviceResolutions[this.deviceResolution].text;
      let pos = restr.lastIndexOf("*");
      let width = parseInt(restr.substring(0, pos));
      let height = parseInt(restr.substring(pos + 1, restr.length));
      let Camid = this.deviceOption;
      this.Cam_Open(Camid, width, height);
    },

    // 开启摄像头
    toOpenCamera() {
      let restr = this.deviceResolutions[this.deviceOption].text;
      let pos = restr.lastIndexOf("*");
      let width = parseInt(restr.substring(0, pos));
      let height = parseInt(restr.substring(pos + 1, restr.length));
      this.Cam_Open(this.deviceOption, width, height);
    },

    // 关闭摄像头
    toCloseCamera() {
      this.Cam_Close();
    },

    // *************设置裁剪模式***************
    SetCameraCutMode() {
      const CutMode = this.clippingMode;
      // this.clippingMode （0：不裁剪，1：自动裁剪，2：手动裁剪）
      const data = JSON.stringify({
        function: "Cam_SetCutMode",
        CutMode: CutMode,
      });
      this.ShowInfo("裁剪模式为：" + CutMode);
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 设置文件格式
    toSetFileType() {
      const filetype = this.filetype;
      this.ShowInfo(
        "文件格式为：" + filetype + ":" + this.fileTypes[filetype].label
      );
      const data = JSON.stringify({
        function: "Cam_SetFileType",
        filetype: filetype,
      });
      this.sho;
      // console.log(this.filetype)
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 设置色彩模式
    toSetColorModel() {
      const colorMode = this.colorModeId;
      const data = JSON.stringify({
        function: "Cam_SetColorMode",
        colorMode: colorMode,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 设置图片质量
    toSetJpgQuality() {
      const data = JSON.stringify({
        function: "Cam_SetJpgQuality",
        quality: this.jpgQualityId,
      });
      this.connected
        ? this.sendMessage(data)
        : ConnectServer(this.sendMessage, data);
      this.ShowInfo("设置的图片质量为：" + this.jpgQualityId);
    },

    // 拍照
    TakePhoto() {
      const name = this.formatDate(new Date().getTime());
      this.imgPath = `${this.path}WDPhotoImg\\${name}`;
      this.toSetFileType();

      switch (this.filetype) {
        case 0:
          this.imgPath = this.imgPath + ".jpg";
          break;
        case 1:
          this.imgPath = this.imgPath + ".png";
          break;
        case 2:
          this.imgPath = this.imgPath + ".tif";
          break;
        case 3:
          this.imgPath = this.imgPath + ".pdf";
          break;
        default:
          this.imgPath = this.imgPath + ".jpg";
          break;
      }
      this.Cam_Photo(this.imgPath); //主摄像头拍照
    },

    // 读身份证
    GetIdCardInfo() {
      // 先将裁剪模式设置为自动裁剪
      this.clippingMode = 1;
      let CutModeDate = JSON.stringify({
        function: "Cam_SetCutMode",
        CutMode: 1,
      });
      this.connected
        ? this.sendMessage(CutModeDate)
        : this.ConnectServer(this.sendMessage, CutModeDate);

      // 然后才能读取身份证信息
      let pathUrl = this.path + "IDCard.jpg";
      let data = JSON.stringify({
        function: "Cam_ReadIdCard",
        cardImgPath: pathUrl,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 添加要合并的图片
    ToAddMergeImageFile() {
      if (this.MergeCount > 4) {
        this.ShowInfo("提示：图像合并最多支持四页合并!");
        return;
      }
      // 如果filepath为空，则为base64
      const filepath = "";
      const data = JSON.stringify({
        function: "Cam_AddMergeImageFile",
        filePath: filepath,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 合并图片
    ToMergeImages() {
      let name = this.formatDate(new Date().getTime());
      let path = `${this.path}${name}.${
        this.fileTypes[this.filetype].label
      }`;
      console.log(path);
      this.MergeCount = 0;
      let data = JSON.stringify({
        function: "Cam_MergeImages",
        filePath: path,
        dir: this.MergeCount,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 添加要合并pdf的文件
    ToAddPDFFile() {
      // 传入的filePath路径为空时，会直接拍照添加
      const data = JSON.stringify({
        function: "Cam_AddImgFileToPDF",
        filePath: "",
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 合并pdf
    ToCombinePDF() {
      const name = this.formatDate(new Date().getTime());
      let pathUrl = `${this.path}${name}.pdf`;
      console.log(pathUrl);
      const data = JSON.stringify({
        function: "Cam_CombinePDF",
        filePath: pathUrl,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 删除文件
    ToDeleteFile() {
      let path = this.imgPath;
      console.log(path);
      const data = JSON.stringify({ function: "DeleteFile", filePath: path });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    /*************************************************公用方法****************************************************************/
    // 时间格式化显示
    formatDate(time) {
      const date = new Date(time);
      const year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      const newTime =
        year +
        (month < 10 ? "0" + month : month) +
        (day < 10 ? "0" + day : day) +
        (hour < 10 ? "0" + hour : hour) +
        (min < 10 ? "0" + min : min) +
        (sec < 10 ? "0" + sec : sec);
      return newTime;
    },

    // 显示信息框体
    ShowInfo(op) {
      const data = {
        text: op
      }
      this.operateRecordList.push(data)
    },

    // 为元素添加监听事件
    addEvent(obj, xEvent, fn) {
      if (obj.attachEvent) {
        obj.attachEvent("on" + xEvent, fn);
      } else {
        obj.addEventListener(xEvent, fn, false);
      }
    },

    /*当鼠标滚轮事件发生时，执行一些操作*/
    onMouseWheel(e) {
      // var ev = ev || window.event;
      let ev = e || window.event;
      let down = true,
        per = 1;
      down = ev.wheelDelta ? ev.wheelDelta < 0 : ev.detail > 0;
      if (down) {
        // 缩小
        const data = JSON.stringify({ function: "Cam_ZoomOut" });
        this.connected
          ? this.sendMessage(data)
          : this.ConnectServer(this.sendMessage, data);
      } else {
        // 放大
        const data = JSON.stringify({ function: "Cam_ZoomIn" });
        this.connected
          ? this.sendMessage(data)
          : this.ConnectServer(this.sendMessage, data);
      }
      return false;
    },

    //*************左旋***************
    Cam_RotateLeft() {
      const data = JSON.stringify({ function: "Cam_RotateLeft" });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
      this.ShowInfo('左旋')
    },

    //*************右旋***************
    Cam_RotateRight() {
      const data = JSON.stringify({ function: "Cam_RotateRight" });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
      this.ShowInfo('右转')
    },
    /*********************
     ***    初始化操作  ***
     **********************/
    LoadCameraDocument() {
      if (!window.WebSocket) {
        alert("浏览器不支持HTML5,请更新或者使用其它浏览器!");
      }
      var obj = document.getElementById("CameraCtl");
      this.Cam_ControlInit(obj, 0, 0, 600, 400);
    },

    //*************摄像头操作初始化***************
    Cam_ControlInit(documentObj, mX, mY, mwidth, mheight) {
      this.ConnectServer(this.sendMessage, ""); //连接服务器
      this.InitCanvas(documentObj, mX, mY, mwidth, mheight); // 初始化画布
      console.log("InitCanvas ok");
    },

    ConnectServer(callback, value) {
      this.ws = new WebSocket(this.url);
      this.ws.onopen = (e) => {
        this.connected = true;
        this.isSocketConnect = true;
        this.heartCheck();
        clearInterval(this.intervalId);
        // 获取设备
        this.Cam_GetDevCount();
      };

      this.ws.onclose = (e) => {
        this.connected = false;
        this.isSocketConnect = true;
        this.reconnect();
      };

      this.ws.onmessage = (e) => {
        this.onMessage(e);
      };

      this.ws.onerror = (e) => {
        this.isSocketConnect = true;
        this.reconnect();
        alert("未连接文豆高拍仪服务，请确保已运行服务端!!!");
      };
    },

    InitCanvas(DivMainBox, mX, mY, mwidth, mheight) {
      if (mwidth != 0 && mheight != 0) {
        const MainCanva = document.createElement("canvas"); // 创建画布
        MainCanva.style.border = "solid 1px #A0A0A0";
        MainCanva.id = "MainCamCanvas";
        MainCanva.width = mwidth;
        MainCanva.height = mheight;
        this.MainContext = MainCanva.getContext("2d");
        this.MainCanvas = MainCanva;
        DivMainBox.appendChild(this.MainCanvas); //添加画布
        // 添加事件
        this.MainCanvas.onmousedown = this.MainCanvasMouseDown;
        this.MainCanvas.onmousemove = this.MainCanvasMouseMove;
        this.MainCanvas.onmouseup = this.MainCanvasMouseUp;
        this.MainCanvas.onmouseout = this.MainCanvasMouseOut;
        this.addEvent(this.MainCanvas, "mousewheel", this.onMouseWheel);
        this.addEvent(this.MainCanvas, "DOMMouseScroll", this.onMouseWheel);
      }
    },

    //*************获取设备数目***************
    Cam_GetDevCount() {
      const data = JSON.stringify({ function: "Cam_GetDevCount" });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    //*************返回获取的设备数目及设备名称***************
    GetDevCountAndNameResultCB(a, b) {
      if (a > 0) {
        this.ShowInfo("找到2个设备");
        for (let i in b) {
          this.deviceOptions.push({
            text: b[i],
            value: Number(i),
          });
        }

        //获取分辨率
        this.Cam_GetDevResolution(this.deviceOption);
      } else {
        this.ShowInfo("没有发现合适的设备！");
      }
    },

    //***************获取分辨率列表***************
    Cam_GetDevResolution(iCamNo) {
      const data = JSON.stringify({
        function: "Cam_GetDevResolution",
        iCamNo: iCamNo,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // ***************分辨率回调函数***************
    GetResolutionResultCB(a, b) {
      if (a > 0) {
        this.deviceResolutions = [];
        for (let i in b) {
          this.deviceResolutions.push({
            text: b[i],
            value: Number(i),
          });
        }
        // 打开摄像头
        this.Cam_Close();
        let restr = this.deviceResolutions[0].text;
        let pos = restr.lastIndexOf("*");
        let width = parseInt(restr.substring(0, pos));
        let height = parseInt(restr.substring(pos + 1, restr.length));
        let Camid = this.deviceOption;
        this.Cam_Open(Camid, width, height);
        this.GetDrives();
      } else {
        this.ShowInfo("获取分辨率信息失败！");
      }
    },

    //*************打开主摄像头***************
    Cam_Open(iCamNo, width, height) {
      const data = JSON.stringify({
        function: "Cam_Open",
        iCamNo: iCamNo,
        width: width,
        height: height,
        viewWidth: this.MainCanvas.width,
        viewHeight: this.MainCanvas.height,
      });
      this.connected
        ? this.sendMessage(data)
        : ConnectServer(this.sendMessage, data);
    },

    //*************关闭摄像头***************
    Cam_Close() {
      const data = JSON.stringify({ function: "Cam_Close", iCamNo: 0 });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
      this.ShowInfo("摄像头关闭");
    },

    //*************返回摄像头状态***************
    GetCameraOnOffStatus(status) {
      if (status == 0) {
        this.ShowInfo("设备开启成功");
      } else {
        this.ShowInfo("设备开启失败!");
      }
    },

    // 手动裁剪区域
    Cam_SetManualCutRect(rectx, recty, rectw, recth) {
      const data = JSON.stringify({
        function: "Cam_SetManualCutRect",
        rectx: rectx,
        recty: recty,
        rectw: rectw,
        recth: recth,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // 图像移动
    MoveOffsetXY(px, py, xdir, ydir) {
      const data = JSON.stringify({
        function: "MoveOffsetXY",
        px: px,
        py: py,
        xdir: xdir,
        ydir: ydir,
      });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // *************获取盘符***************
    GetDrives() {
      const data = JSON.stringify({ function: "GetDrives" });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    //*************拍照***************
    Cam_Photo(filePath) {
      this.ShowInfo(filePath)
      if (this.clippingMode == 2) {
        let rectx, recty, rectw, recth;
        if (this.pALastX > this.pACurrentX) {
          rectx = this.pACurrentX;
        } else {
          rectx = this.pALastX;
        }
        if (this.pALastY > this.pACurrentY) {
          recty = this.pACurrentY;
        } else {
          recty = this.pALastY;
        }
        rectw = Math.abs(this.pACurrentX - this.pALastX);
        recth = Math.abs(this.pACurrentY - this.pALastY);
        this.Cam_SetManualCutRect(rectx, recty, rectw, recth); //手动裁剪区域
      }
      const data = JSON.stringify({
        function: "Cam_Photo",
        filePath: filePath,
      });
      this.ShowInfo(data);
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(this.sendMessage, data);
    },

    // *************拍照结果***************
    GetCaptrueImgResultCB(flag, path, base64Str) {
      if (flag == 0) {
        this.file_path = path;
        this.fileBase64Str = base64Str;
        let obj = document.getElementById("CameraPhoto");
        obj.src = "data:;base64," + base64Str;
        if (path == "") {
          this.ShowInfo("拍照成功");
        } else {
          this.ShowInfo("拍照成功，图片保存位置：" + path);
        }
      } else {
        this.ShowInfo("拍照失败!");
      }
    },

    // *************读取身份证后调用的回调函数***************
    GetIdCardInfoResultCB(flag, resultStr) {
      if (flag == 0) {
        this.IDCardObject.name = resultStr[0];
        this.IDCardObject.sex = resultStr[1];
        this.IDCardObject.nation = resultStr[2];
        this.IDCardObject.birth = resultStr[3];
        this.IDCardObject.register = resultStr[4];
        this.IDCardObject.idCard = resultStr[5];
        this.ShowInfo(Object.values(this.IDCardObject).join(','));
      } else {
        this.ShowInfo("读卡失败");
      }
    },

    //  *************添加合并图片的函数***************
    AddMergeImageFileResultCB(flag, base64Str) {
      if (flag == 0) {
        this.ShowInfo("图像合并成功");
        let obj = document.getElementById("CameraPhoto");
        obj.src = "data:;base64," + base64Str;
      } else {
        this.ShowInfo("添加合并图像文件失败!");
      }
    },

    // *************合并图片调用的回调函数***************
    MergeImagesResultCB(flag, PdfBase64Str) {
      if (flag == 0) {
        this.ShowInfo("合并图片完成");
        console.log(this.path);
      } else {
        this.ShowInfo("合并P图片失败!");
      }
    },

    //  *************添加合并pdf的函数***************
    AddImgFileToPDFResultCB(flag, base64Str) {
      if (flag == 0) {
        this.ShowInfo("添加合并的PDF文件成功");
        let obj = document.getElementById("CameraPhoto");
        obj.src = "data:;base64," + base64Str;
      } else {
        this.ShowInfo("添加合并的PDF文件失败!");
      }
    },

    // *************合并pdf调用的回调函数***************
    PdfCombineResultCB(flag, PdfBase64Str) {
      if (flag == 0) {
        this.ShowInfo("合并PDF完成");
        console.log(this.path);
      } else {
        this.ShowInfo("合并PDF失败!");
      }
    },

    // ************删除文件调用的回调函数***************
    GetDeleteFileResultCB(flag) {
      if (flag == 0) {
        this.ShowInfo("删除文件成功");
        let obj = document.getElementById("CameraPhoto");
        obj.src = "";
        this.imgPath = "";
      } else {
        this.ShowInfo("删除文件失败！");
      }
    },

    /**********************************************websocket 调用函数回调*******************************************************************/
    cameraProduceMessage(jsonObj) {
      // websocket 返回主摄像头码流信息 base64位格式
      if (jsonObj.functionName == "VideoStream") {
        let bstr = atob(jsonObj.imgBase64Str);
        let n = bstr.length;
        if (n == jsonObj.width * jsonObj.height * 3) {
          this.MainContext.clearRect(
            0,
            0,
            this.MainCanvas.width,
            this.MainCanvas.height
          );
          let imgData = this.MainContext.createImageData(
            jsonObj.width,
            jsonObj.height
          );
          let dataNum = 0;
          for (var i = 0; i < imgData.data.length; i += 4) {
            imgData.data[i + 3] = 255;
            imgData.data[i + 0] = bstr.charCodeAt(dataNum);
            imgData.data[i + 1] = bstr.charCodeAt(dataNum + 1);
            imgData.data[i + 2] = bstr.charCodeAt(dataNum + 2);
            imgData.data[i + 3] = 255;
            dataNum = dataNum + 3;
          }
          let pMainShowStartX = jsonObj.StartX;
          let pMainShowStartY = jsonObj.StartY;
          this.MainContext.putImageData(
            imgData,
            pMainShowStartX,
            pMainShowStartY
          );

          // 如果为手动裁剪
          if (this.clippingMode == 2) {
            this.MainContext.strokeStyle = "blue";
            this.MainContext.lineWidth = 2;
            this.MainContext.beginPath();
            this.MainContext.rect(
              this.pALastX,
              this.pALastY,
              this.pACurrentX - this.pALastX,
              this.pACurrentY - this.pALastY
            );
            this.MainContext.closePath();
            this.MainContext.stroke();
          }
        }
      }

      // websocket 返回设备列表,调用设备列表分辨率信息回调函数GetDevCountAndNameResultCB
      if (jsonObj.functionName == "Cam_GetDevCount") {
        let camName = new Array();
        camName = jsonObj.DevName.split("|");
        this.GetDevCountAndNameResultCB(jsonObj.DevCount, camName);
      }

      // websocket 返回分辨率,调用回调函数GetResolutionResultCB
      if (jsonObj.functionName == "Cam_GetDevResolution") {
        let resArr = new Array();
        resArr = jsonObj.Resolution.split("|");
        this.GetResolutionResultCB(jsonObj.ResolutionCount, resArr);
      }

      // websocket 返回摄像头状态, 调用回调函数GetCameraOnOffStatus
      if (jsonObj.functionName == "Cam_Open") {
        let status = jsonObj.success;
        if (status == 0) {
          this.isOpenMainCamera = true;
          this.GetCameraOnOffStatus(0);
        } else {
          this.isOpenMainCamera = false;
          this.GetCameraOnOffStatus(-1);
        }
      }

      //  websocket 返回盘符信息
      if (jsonObj.functionName == "GetDrives") {
        if (jsonObj.DrivesName == "") {
          this.ShowInfo("获取盘符失败!");
        }
        let DrivesName = jsonObj.DrivesName.split("\\").filter(function (e) {
          return e && e.trim();
        });
        if (DrivesName.length >= 2) {
          this.path = `${DrivesName[1]}\\Program Files\\`;
          console.log(this.path);
        } else {
          this.path = `${DrivesName[0]}\\Program Files\\`;
        }
        this.ShowInfo(this.path);
      }

      // websocket 返回拍照结果, 调用回调函数GetCaptrueImgResultCB
      if (jsonObj.functionName == "Cam_Photo") {
        const filePath = decodeURIComponent(jsonObj.filePath);
        this.GetCaptrueImgResultCB(jsonObj.success, filePath, jsonObj.base64);
        this.ShowInfo(`拍照结果：${filePath}`);
      }

      // websocket 返回读取身份证结果, 调用回调函数GetIdCardInfoResultCB
      if (jsonObj.functionName == "Cam_ReadIdCard") {
        console.log("4");
        if (jsonObj.success == 0) {
          let resultStr = new Array();
          let decodeStr = decodeURIComponent(jsonObj.CardInfo);
          resultStr = decodeStr.split(";");
          this.GetIdCardInfoResultCB(jsonObj.success, resultStr);
        } else {
          this.GetIdCardInfoResultCB(jsonObj.success, resultStr);
        }
      }

      // websocket 返回添加合并图片文件的结果, 调用回调函数AddMergeImageFileResultCB
      if (jsonObj.functionName == "Cam_AddMergeImageFile") {
        this.AddMergeImageFileResultCB(jsonObj.success, jsonObj.base64);
      }

      // websocket 返回合并图片文件的结果, 调用回调函数MergeImagesResultCB
      if (jsonObj.functionName == "Cam_MergeImages") {
        this.MergeImagesResultCB(jsonObj.success, jsonObj.base64);
      }

      // websocket 返回添加合并pdf文件的结果, 调用回调函数AddImgFileToPDFResultCB
      if (jsonObj.functionName == "Cam_AddImgFileToPDF") {
        this.AddImgFileToPDFResultCB(jsonObj.success, jsonObj.base64);
      }

      // websocket 返回合并pdf文件的结果, 调用回调函数PdfCombineResultCB
      if (jsonObj.functionName == "Cam_CombinePDF") {
        this.PdfCombineResultCB(jsonObj.success, jsonObj.base64);
      }

      // websocket 返回合并pdf文件的结果, 调用回调函数PdfCombineResultCB
      if (jsonObj.functionName == "DeleteFile") {
        this.GetDeleteFileResultCB(jsonObj.success);
      }
    },

    /*************************************************websocket心跳重置及操作****************************************************************/
    Heartbeat() {
      const data = JSON.stringify({ function: "Heartbeat" });
      this.connected
        ? this.sendMessage(data)
        : this.ConnectServer(sendMessage, data);
    },

    heartCheck() {
      clearInterval(this.heartTimerId);
      this.heartTimerId = setInterval(() => {
        if (this.isSocketConnect) {
          this.Heartbeat();
        }
      }, 6500);
    },

    /**
     * 向服务器发送信息的共享方法
     * @param jsonStr
     */
    sendMessage(jsonStr) {
      this.connected
        ? this.ws.send(jsonStr)
        : alert("未连接websocket服务器，请确保已运行服务端！");
    },

    /**
     * 接收服务器消息
     * @param e
     */
    onMessage(e) {
      const Obj = JSON.parse(e.data.replace(/[\r\n]/g, ""));
      //通用回调处理函数 jsonObj
      this.cameraProduceMessage(Obj);
    },

    reconnect() {
      clearInterval(this.intervalId);
      this.intervalId = setInterval(function () {
        if (this.isSocketConnect == false) {
          this.Heartbeat();
          console.log("reconnect...");
        }
        console.log("reconnectTimer.........!");
      }, 3000);
    },

    // 鼠标事件
    MainCanvasMouseDown(e) {
      this.isMouseDown = true;
      this.pALastX = e.pageX - this.MainCanvas.offsetLeft;
      this.pALastY = e.pageY - this.MainCanvas.offsetTop;
      if (this.clippingMode == 2) {
        this.pACurrentX = this.pALastX;
        this.pACurrentY = this.pALastY;
      }
    },
    MainCanvasMouseMove(e) {
      if (this.isMouseDown) {
        if (this.clippingMode == 2) {
          this.pACurrentX = e.pageX - this.MainCanvas.offsetLeft;
          this.pACurrentY = e.pageY - this.MainCanvas.offsetTop;
          let rectx, recty, rectw, recth;
          if (this.pALastX > this.pACurrentX) {
            rectx = this.pACurrentX;
          } else {
            rectx = this.pALastX;
          }
          if (this.pALastY > this.pACurrentY) {
            recty = this.pACurrentY;
          } else {
            recty = this.pALastY;
          }
          rectw = Math.abs(this.pACurrentX - this.pALastX);
          0;
          recth = Math.abs(this.pACurrentY - this.pALastY);
          this.Cam_SetManualCutRect(rectx, recty, rectw, recth); //手动裁剪区域
        } else {
          this.pACurrentX = e.pageX - this.MainCanvas.offsetLeft;
          this.pACurrentY = e.pageY - this.MainCanvas.offsetTop;
          let dx = this.pACurrentX - this.pALastX;
          let dy = this.pACurrentY - this.pALastY;
          let xdir = 0;
          let ydir = 0;
          if (dx < 0) {
            xdir = 0;
          } else {
            xdir = 1;
          }
          if (dy < 0) {
            ydir = 0;
          } else {
            ydir = 1;
          }
          this.pALastX = this.pACurrentX;
          this.pALastY = this.pACurrentY;
          this.MoveOffsetXY(Math.abs(dx), Math.abs(dy), xdir, ydir);
        }
      }
    },
    MainCanvasMouseUp() {
      this.isMouseDown = false;
    },
    MainCanvasMouseOut() {
      this.isMouseDown = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.wendouDiv{
  margin-top: 4px;
  .operateRecord{
    width: 280px;
    background: transparent;
    margin-right: 10px;
    border: 1px solid #a5bcff;
    border-radius: 4px;
    box-shadow: 0px 0px 4px #a5bcff;
    transition: box-shadow 0.4s;
    &_title{
      padding: 10px 8px;
      color: #000;
      font-size: 14px;
      background: linear-gradient(-90deg, #f1eefc,#9dc6ff 70%,#a5bcff) no-repeat right bottom;
                  // linear-gradient(-90deg, #f1eefc,#9dc6ff 70%,#a5bcff) no-repeat left top;
      background-size: 0% 100% /*, 4px 0px */;
      transition: background-size 0.4s;
      border-bottom:1px solid #a5bcff;
      &:hover{
        color: #fff;
        background-size: 100% 100%/* , 4px 100% */;
        background-position-x:left;
        // background-position-y:bottom;
      }
    }
    &_Main{
      height: 300px;
      width: 100%;
      overflow-y: auto;
      span{
        display: block;
        margin-top: 4px;
        width: 100%;
        position: relative;
        white-space: pre-wrap;
        &::before{
          content: '';
          height: 2px;
          background: linear-gradient(-90deg, #f1eefc,#9dc6ff 70%,#a5bcff) no-repeat left bottom;
          position: absolute;
          bottom: -2px;
          animation: leftToRight 0.4s forwards;
        }
      }
    }

    /*控制整体*/
    &_Main::-webkit-scrollbar{
      width: 8px;
      height: 8px;
    }
    /*控制滑块*/
    &_Main::-webkit-scrollbar-track{
      background: #ededed;
      border-radius: 4px;
    }
    /*控制轨道*/
    &_Main::-webkit-scrollbar-thumb{
      border-radius: 4px;
      background: #b7b7b7;
    }
    /*控制交汇处*/
    &_Main::-webkit-scrollbar-corner{
      background: #b7b7b7;
      border-radius: 4px;
    }

    &:hover{
      box-shadow: 2px 2px 8px #a5bcff;
    }
  }
  .wendouMain{
    width: 610px;
    .Div1{
      width: 600px;
      height: 400px;
      .CameraCtl{
        width: 600px;
        height: 400px;
        float: left;
      }
    }
    .wendou_operateList{
      border: 1px solid #a5bcff;
      width: 100%;
      .operateList_title{
        background: linear-gradient(-90deg, #f1eefc,#9dc6ff 70%,#a5bcff);
        padding: 10px 12px;
        font-size: 18px;
        color: #fff;
        font-weight: 700;
      }
    }
  }
}
@keyframes leftToRight {
  from{
    width: 0px;
  }
  to{
    width: 100%;
  }
}
</style>